from application import jsonrpc,redis
from ronglian_sms_sdk import SmsSDK
from flask import current_app
import random,re,json
from status import APIStatus as status
from message import ErrorMessage as message
from flask import request
import requests
@jsonrpc.method(name="Home.sms")
def sms(ticket,randstr,mobile):
	'''发送短信验证码'''

	params = {
		"aid": current_app.config.get("CAPTCHA_APP_ID"),
		"AppSecretKey": current_app.config.get("CAPTCHA_APP_SECRET_KEY"),
		"Ticket": ticket,
		"Randstr": randstr,
		"UserIP": request.remote_addr
	}
	""" 2. requests方法 """
	url = current_app.config.get("CAPTCHA_GATEWAY") + "?"
	response = requests.get(url, params=params)
	content = response.text
	res = json.loads(content)
	# print(res,type(res))

	if int(res.get("response")) != 1:
		# 验证失败
		return {"errno": status.CODE_CAPTCHA_ERROR, "errmsg": message.captcaht_no_match}

	# 验证手机
	if not re.match("^1[3-9]\d{9}$",mobile):
		return {"errno":status.CODE_VALIDATE_ERROR,"errmsg":message.mobile_format_error}

	# 短信发送冷却时间
	ret = redis.get("int_%s" % mobile)
	if ret is not None:
		return {"errno": status.CODE_INTERVAL_TIME, "errmsg": message.sms_interval_time}

	# 生成验证码
	sms_code = "%06d" % random.randint(0, 999999)

	try:
		# 异步发送短信
		from mycelery.sms.tasks import send_sms2
		send_sms2.delay(mobile=mobile,sms_code=sms_code)

		# 返回结果
		return {"errno": status.CODE_OK, "errmsg": message.sms_is_send}
	except Exception as e:
		return {"errno": status.CODE_SMS_ERROR, "errmsg": message.sms_send_error}








